import 'dart:async';

import 'package:chewie/chewie.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_bilibili/core/extension/int_extension.dart';
import 'package:flutter_bilibili/core/model/video_model.dart';
import 'package:flutter_bilibili/ui/pages/video_play/dan_mu_2/dan_mu_proto.dart';
import 'package:flutter_bilibili/ui/pages/video_play/video/video_play_comments.dart';
import 'package:flutter_bilibili/ui/pages/video_play/video/video_play_profile.dart';
import 'package:flutter_bilibili/ui/pages/video_play/video/video_play_initialize_item.dart';
import 'package:flutter_bilibili/ui/shared/app_theme.dart';
import 'package:video_player/video_player.dart';

import '../../../widgets/bilibili_controls.dart';

class HYVideoPlayContent extends StatefulWidget {
  HYVideoModel video;
  double aspectRatio;

  HYVideoPlayContent({Key? key, required this.video, required this.aspectRatio})
      : super(key: key);

  @override
  State<HYVideoPlayContent> createState() => _HYVideoPlayContentState();
}

class _HYVideoPlayContentState extends State<HYVideoPlayContent> {
  // final _danMuKey = GlobalKey<DanMuState>();
  var tabTitle = ['简介', '评论'];

  ///视频播放
  late VideoPlayerController _videoPlayerController;
  late ChewieController _chewieController;
  bool isLoadingAccomplished = false;

  @override
  void initState() {
    ///视频初始化
    _videoPlayerController =
        VideoPlayerController.network(widget.video.videoData);
    _videoPlayerController.initialize().then((value) {
      _chewieController = ChewieController(
        allowMuting: false,
        videoPlayerController: _videoPlayerController,
        autoPlay: true,
        customControls: HYBilibiliControls(
          video: widget.video,
        ),
        // customControls: MaterialControls()
      );
      isLoadingAccomplished = true;
      if (mounted) {
          setState(() {});
        }
      });

    ///隐藏顶部的状态栏
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: [SystemUiOverlay.bottom]);
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return DefaultTabController(
      length: tabTitle.length,
      initialIndex: 0,
      child: Scaffold(
        appBar: AppBar(
          leading: Container(),
          elevation: .4,
          toolbarHeight: 280.px,
          flexibleSpace: buildVideoPlayVideoPlayer(),
          bottom: buildVideoPlayTabBar(context),
        ),
        body: buildVideoPlayTabBarView(),
      ),
    );
  }

  @override
  void dispose() {
    _videoPlayerController.dispose();
    _chewieController.dispose();

    ///推出视频播放界面就将顶部状态栏加上
    SystemChrome.setEnabledSystemUIMode(SystemUiMode.manual,
        overlays: [SystemUiOverlay.top, SystemUiOverlay.bottom]);
    super.dispose();
  }

  ///leading
  Widget buildVideoPlayLeading() {
    return IconButton(
        onPressed: () {
          Navigator.of(context).pop();
        },
        icon: Image.asset(
          "assets/image/icon/back_custom.png",
          width: videoPlayIconSize,
          height: videoPlayIconSize,
        ));
  }

  ///TabBarView
  Widget buildVideoPlayTabBarView() {
    return TabBarView(
      children: tabTitle.map((e) {
        if (e == "简介") {
          return HYVideoPlayProfile(widget.video);

          ///视频简介
        } else {
          return HYVideoPlayComments();

          ///评论
        }
      }).toList(),
    );
  }

  ///TabBar
  PreferredSizeWidget buildVideoPlayTabBar(BuildContext context) {
    return PreferredSize(

        ///tab设置底色
        preferredSize: Size.fromHeight(7.px),
        child: Material(
          color: Colors.white,
          child: TabBar(
            tabs: tabTitle.map((e) => Tab(text: e)).toList(),
            indicatorColor: HYAppTheme.norTextColors,
            unselectedLabelColor: HYAppTheme.unselectedLabelColor,
            labelColor: HYAppTheme.norTextColors,
            indicatorSize: TabBarIndicatorSize.label,
            labelStyle: const TextStyle(
                fontWeight: FontWeight.bold,
                fontSize: HYAppTheme.xxSmallFontSize),
            unselectedLabelStyle: const TextStyle(
                fontWeight: FontWeight.normal,
                fontSize: HYAppTheme.xxSmallFontSize),
            indicatorWeight: 4.px,
            labelPadding: EdgeInsets.zero,
            indicatorPadding: EdgeInsets.only(bottom: 10.px),
          ),
        ));
  }

  ///Action
  List<Widget> buildVideoPlayActions() {
    return [
      IconButton(
          onPressed: () => print("mini_window_custom"),
          icon: Image.asset(
            "assets/image/icon/mini_window_custom.png",
            width: videoPlayIconSize,
            height: videoPlayIconSize,
          )),
      IconButton(
          onPressed: () => print("tv_play_custom"),
          icon: Image.asset(
            "assets/image/icon/tv_play_custom.png",
            width: videoPlayIconSize,
            height: videoPlayIconSize,
          )),
      IconButton(
          onPressed: () => print("video_player_more_custom"),
          icon: Image.asset(
            "assets/image/icon/video_player_more_custom.png",
            width: videoPlayIconSize,
            height: videoPlayIconSize,
          )),
    ];
  }

  ///视频和弹幕
  Widget buildVideoPlayVideoPlayer() {
    double width = MediaQuery.of(context).size.width;
    // print(widget.video.duration ~/ 60);
    return Container(
      height: 260.px,
      color: Colors.black,
      padding: EdgeInsets.symmetric(vertical: 10.px),
      child: Center(
        child: Stack(
          children: [
            isLoadingAccomplished == true
                ? AspectRatio(
                    aspectRatio: _chewieController
                        .videoPlayerController.value.aspectRatio,
                    child: Chewie(controller: _chewieController),
                  )
                : Center(
                    child: Container(
                      width: 40.px,
                      height: 40.px,
                      child: CircularProgressIndicator(
                        color: HYAppTheme.norTextColors,
                      ),
                    ),
                  ),

            /// 忽略弹幕的点击事件，将点击传递给视频
            IgnorePointer(
              child: BuildDanMuProtoScreen(
                width: width,
                oid: widget.video.cid,

                ///转为多少分钟，整除
                duration: widget.video.duration ~/ 60,
              ),
            )
          ],
        ),
      ),
    );
  }
}
